package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.entity.Course;
import com.zzw.springboot.entity.StudentCourse;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.mapper.CourseMapper;
import com.zzw.springboot.service.ICourseService;
import com.zzw.springboot.service.IStudentCourseService;
import com.zzw.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzw
 * @since 2022-06-10 16:17:35
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IStudentCourseService studentCourseService;

    @Override
    public Page<Course> findPage(Page<Course> page, String name) {
        Page<Course> coursePage = page(page, Wrappers.<Course>lambdaQuery()
                .like(StringUtils.isNotEmpty(name), Course::getName, name)
                .orderByDesc(Course::getId));
        List<Course> courses = coursePage.getRecords().stream().peek(course -> {
            String nickname = userService.getOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getId, course.getTeacherId())).getNickname();
            course.setTeacher(nickname);
        }).collect(Collectors.toList());
        coursePage.setRecords(courses);
        return coursePage;
    }

    @Override
    @Transactional
    public void studentCourse(Integer courseId, Integer studentId) {
        studentCourseService.remove(Wrappers.<StudentCourse>lambdaQuery()
                .eq(StudentCourse::getCourseId, courseId)
                .eq(StudentCourse::getStudentId, studentId));
        studentCourseService.save(new StudentCourse(studentId,courseId));
    }
}
